package indi.jp.project.business.jingying.service.impl;

import indi.jp.project.core.entity.Datagrid;
import indi.jp.project.core.entity.JsonResult;
import indi.jp.project.core.util.SerialUtil;
import indi.jp.project.business.jingying.dao.SuppliesDAO;
import indi.jp.project.business.jingying.entity.Supplies;
import indi.jp.project.business.jingying.entity.SuppliesItem;
import indi.jp.project.business.jingying.pojo.query.SuppliesQuery;
import indi.jp.project.business.jingying.service.SuppliesService;
import indi.jp.project.process.service.FlowTaskService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 经营用品Service实现
 *
 * @author jiangping
 * @date 2022/5/7
 */
@Service
public class SuppliesServiceImpl implements SuppliesService {

    @Resource
    private SuppliesDAO suppliesDAO;

    @Resource
    private SerialUtil serialUtil;

    @Resource
    private FlowTaskService flowTaskService;

    @Override
    public JsonResult queryGrid(SuppliesQuery query) throws Exception {
        List<Supplies> list = suppliesDAO.queryList(query);
        int count = suppliesDAO.queryCount(query);
        Datagrid<Supplies> datagrid = new Datagrid<>(list, count);
        return JsonResult.success(datagrid);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult save(Supplies supplies) throws Exception {
        String id;
        if (StringUtils.isBlank(supplies.getId())) {
            id = String.valueOf(serialUtil.nextId());
            supplies.setId(id);
            suppliesDAO.insert(supplies);
        } else {
            id = supplies.getId();
            suppliesDAO.update(supplies);
            suppliesDAO.deleteItemsByPId(id);
        }
        List<SuppliesItem> items = supplies.getItems();
        for (SuppliesItem item : items) {
            item.setBillId(id);
            item.setId(String.valueOf(serialUtil.nextId()));
        }
        suppliesDAO.insertItems(items);
        flowTaskService.saveTaskFlow(id, supplies.getFlowList());
        return JsonResult.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult deleteById(String id) throws Exception {
        suppliesDAO.deleteById(id);
        suppliesDAO.deleteItemsByPId(id);
        flowTaskService.deleteFlowByTaskId(id);
        return JsonResult.success();
    }

    @Override
    public JsonResult findById(String id) throws Exception {
        Supplies supplies = suppliesDAO.findById(id);
        List<SuppliesItem> items = suppliesDAO.queryItemList(id);
        supplies.setItems(items);
        return JsonResult.success(supplies);
    }
}
